<template>
  <div class="functional-calculation">
    <div class="functional-calculation-left" ref="functionalCalculationLeft">
      <div class="functional-calculation-left-in">
        <div class="btns" ref="mainBodyLeftHead3">
          <el-button
            type="primary"
            class="el-btn"
            size="mini"
            @click="importFile()"
          >
            <svg-icon icon-class="uploadfiles" />
            导入
          </el-button>
          <el-button
            type="primary"
            class="el-btn"
            size="mini"
            @click="deleteFile()"
          >
            <svg-icon icon-class="deletefile" />
            删除
          </el-button>
        </div>
        <div>
          <ul class="file-list" :style="{ height: leftFilelistHeight }">
            <li v-if="closestPackingFileImportList.length">
              <div :class="['file-check-box']" @click="filesListSelectAll()">
                <svg-icon icon-class="check2" v-if="isFilesListSelectAll" />
              </div>
              <div class="file-list-select-txt">全选</div>
            </li>

            <li v-for="(item, key) in closestPackingFileImportList" :key="key">
              <div :class="['file-check-box']" @click="checkfile(item)">
                <svg-icon
                  icon-class="check2"
                  v-if="closestPackingDataManageSel.includes(item)"
                />
              </div>
              <div class="file-body">
                {{ item }}
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="functional-calculation-center">
      <div class="btns" ref="functionalCalculationCenterHead">
        <el-button
          type="primary"
          class="el-btn"
          size="mini"
          @click="showDrawChartDialog()"
        >
          <svg-icon icon-class="drawchart" />
          绘制图表
        </el-button>
      </div>
      <div class="chart-body">
        <div
          id="closestPacking"
          class="chart"
          ref="closestPacking"
          :style="{ width: chartWidth, height: chartHeight }"
        ></div>

        <div class="chart-menu" ref="chartMenu">
          <ul class="chart-menu-in" :style="{ height: chartHeight }">
            <li
              v-for="(item, key) in results"
              :key="key"
              @click="chartForChoose(key)"
              :class="[chartChooseActive.includes(key) ? 'active' : '']"
            >
              <div class="chart-menu-index">{{ key + 1 }}</div>
              <div class="chart-menu-file">
                <div class="chart-menu-file-body">
                  <div class="chart-menu-file-name chart-menu-title">
                    文件名
                  </div>
                  <div class="chart-menu-file-v chart-menu-title">体积分数</div>
                  <div class="chart-menu-file-w chart-menu-title">质量分数</div>
                </div>
                <div
                  v-for="(combination, CombinationKey) in item.Combination"
                  :key="CombinationKey"
                  class="chart-menu-file-body"
                >
                  <div class="chart-menu-file-name">{{ combination }}</div>
                  <div class="chart-menu-file-v">
                    {{ item["V"][CombinationKey].toFixed(4) }}
                  </div>
                  <div class="chart-menu-file-w">
                    {{ item["W"][CombinationKey].toFixed(4) }}
                  </div>
                </div>
                <div class="chart-menu-r">
                  <div>相关性系数：</div>
                  <div class="chart-menu-r-value">
                    {{ item["R2"].toFixed(4) }}
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="drawChartDialog"
      :close-on-click-modal="false"
      :before-close="drawChartDialogCancel"
      title="参数"
      append-to-body
      width="500px"
      @close="drawChartDialogCancel"
    >
      <el-form
        ref="form"
        label-width="auto"
        :model="form"
        :rules="rules"
        size="mini"
      >
        <el-form-item label="几元复配" prop="n_comps">
          <el-input
            v-model="form.n_comps"
            @input="(e) => handleEdit(e, 'n_comps')"
            class="horizontal-val"
            :placeholder="n_comps_placeholder"
            clearable
          />
        </el-form-item>
        <el-form-item label="分布模数" prop="n">
          <el-input
            v-model="form.n"
            @input="(e) => handleEdit(e, 'n')"
            class="horizontal-val"
            placeholder="请输入分布模数"
            clearable
          />
        </el-form-item>
        <el-form-item label="材料密度" prop="new_name">
          <ul class="material-density">
            <li v-for="(item, key) in selectFile" :key="key">
              <div class="material-density-name">{{ item }}</div>
              <el-input
                v-model="form.w[key]"
                @blur="(e) => checkw(e, key)"
                clearable
                class="material-density-val"
              ></el-input>
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="填充率" prop="fill_rate">
          <el-input
            v-model="form.fill_rate"
            @input="(e) => handleEdit(e, 'fill_rate')"
            class="horizontal-val"
            placeholder="请输入填充率"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="drawChartDialogCancel" class="cancel-btn"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="drawChartDialogCheck"
          class="checkok-btn"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  get_files,
  upload,
  get_detile,
  curve_intersections,
  horizontal_intersections,
  points,
  merge,
  rename,
  dataManageDel,
  get_config_parameters,
  densest_accumulation_all,
} from "@/api/index";
import { deepClone } from "@/utils";
export default {
  name: "HelloWorld",
  props: {
    user_name: {
      type: String,
      default: "",
    },
    leftFilelistHeight: {
      type: String,
      default: "",
    },
    user_id: {
      type: String,
      default: "",
    },
    chartHeight: {
      type: String,
      default: "",
    },
    chartWidth: {
      type: String,
      default: "",
    },
    closestPackingFileImportList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    chartWidth: function () {
      this.$nextTick(() => {
        if (this.myChart) this.myChart.resize();
      });
    },
    chartHeight: function () {
      this.$nextTick(() => {
        if (this.myChart) this.myChart.resize();
      });
    },
  },
  computed: {
    compouteIntersection() {
      return (item) => {
        return this.selectIntersectionDot.findIndex((iitem) => iitem === item);
      };
    },
    computeRound() {
      return (val, num) => {
        let n = 4;
        if (num) {
          n = num;
        }
        return (Math.round(val * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n);
      };
    },
  },
  data() {
    const n_comps_pattern = (rule, value, callback) => {
      if (
        !(
          /^[1-9]\d?$/.test(value) &&
          value >= 2 &&
          value <= this.closestPackingDataManageSel.length
        )
      ) {
        callback(
          new Error(
            "请输入大于等于2,小于等于" +
              this.closestPackingDataManageSel.length +
              "的整数"
          )
        );
      } else {
        callback();
      }
    };
    const n_pattern = (rule, value, callback) => {
      console.log(value, "###value");
      if (value === "0") {
        callback(new Error("请输入大于0的数"));
      } else {
        callback();
      }
    };

    const fill_rate_pattern = (rule, value, callback) => {
      if (!(Number(value) >= 0 && Number(value) <= 1)) {
        callback(new Error("请输入大于等于0,小于等于1的数字"));
      } else {
        callback();
      }
    };

    return {
      isFilesListSelectAll: false,
      n_comps_placeholder: "",
      drawChartDialog: false,

      m_value: 0.37,
      allintersectiondot: [],
      selectIntersectionDot: [],
      closestPackingDataManageSel: [],
      closestPackingImportSelectKey: [],
      intersectionVals: [],
      selectFile: [],
      form: {
        n: "",
        n_comps: "",
        w: [],
        fill_rate: "",
      },
      rules: {
        n_comps: [
          { validator: n_comps_pattern, required: true, trigger: "blur" },
        ],
        n: [{ validator: n_pattern, required: false, trigger: "blur" }],
        fill_rate: [
          { validator: fill_rate_pattern, required: false, trigger: "blur" },
        ],
      },
      results: [],
      ideal_distribution: [],
      x_values: [],
      chartChooseActive: [],
      myChart: null,
    };
  },
  methods: {
    filesListSelectAll() {
      if (this.isFilesListSelectAll) {
        this.isFilesListSelectAll = false;
        this.closestPackingDataManageSel = [];
      } else {
        this.isFilesListSelectAll = true;
        this.closestPackingDataManageSel = deepClone(
          this.closestPackingFileImportList
        );
      }
    },

    chartForChoose(index) {
      let _index = this.chartChooseActive.indexOf(index);
      if (_index > -1) {
        this.chartChooseActive.splice(_index, 1);
      } else {
        this.chartChooseActive = [...this.chartChooseActive, index];
      }
      this.getchart();
    },
    handleEdit(e, type) {
      let value = e.replace(/[^\d.]/g, "").replace(/\.{2,}/g, ".");
      this.form[type] = value;
    },
    drawChartDialogCheck() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.myChart) this.myChart.clear();
          this.results = [];
          this.ideal_distribution = [];
          this.x_values = [];
          this.chartChooseActive = [];

          this.drawChart();
          this.drawChartDialogCancel();
        } else {
        }
      });
    },
    drawChartDialogCancel() {
      this.drawChartDialog = false;
      this.n_comps_placeholder = "";
      this.form["n_comps"] = "";
      this.form["n"] = "";
      this.form["w"] = [];
    },
    checkw(e, key) {
      let value = e.target.value.replace(/[^\d.]/g, "").replace(/\.{2,}/g, ".");
      this.form.w[key] = value;
    },
    showDrawChartDialog() {
      if (!(this.closestPackingDataManageSel.length >= 2)) {
        this.$message({
          type: "error",

          message: "请选择2个以上文件",
        });
        return;
      }
      this.closestPackingDataManageSel.map((item, key) => {
        this.form.w[key] = "";
      });

      this.selectFile = deepClone(this.closestPackingDataManageSel);
      this.drawChartDialog = true;
      this.n_comps_placeholder =
        "请输入大于等于2,小于等于" +
        this.closestPackingDataManageSel.length +
        "的整数";
    },
    importFile() {
      this.$emit(
        "showFilesListDialog",
        "closestPacking",
        deepClone(this.closestPackingFileImportList)
      );
    },
    chooseIntersectionDot(item) {
      let index = this.selectIntersectionDot.findIndex(
        (iitem) => iitem === item
      );

      if (index > -1) {
        this.selectIntersectionDot.splice(index, 1);
      } else {
        this.selectIntersectionDot.push(item);
      }
    },
    deleteFile() {
      let closestPackingFileImportList =
        this.closestPackingFileImportList.filter(
          (item, index) => !this.closestPackingDataManageSel.includes(item)
        );
      this.$emit(
        "update:closestPackingFileImportList",
        closestPackingFileImportList
      );
      this.closestPackingDataManageSel = [];
    },
    async checkfile(item) {
      let _index = this.closestPackingDataManageSel.indexOf(item);
      if (_index > -1) {
        this.closestPackingDataManageSel.splice(_index, 1);
      } else {
        this.closestPackingDataManageSel.push(item);
      }
    },

    async drawChart() {
      if (!this.closestPackingDataManageSel.length) {
        this.$message({
          type: "error",
          message: "请选择文件",
        });
        return;
      }

      let file_names = deepClone(this.closestPackingDataManageSel);

      let w = [];
      this.form.w.map((item) => {
        w = [...w, Number(item)];
      });

      let data = {
        user_id: this.user_id,
        user_name: this.user_name,
        file_names,
        n_comps: Number(this.form.n_comps),
        w: w,
        fill_rate: Number(this.form.fill_rate),
      };
      let n = Number(this.form.n);
      if (n > 0) {
        data["n"] = n;
      }
      let res = await densest_accumulation_all(data);
      let ideal = res.ideal_distribution;
      let ideal_distribution = [];
      let results = res.results;

      for (let i = 0; i < res.x_values.length; i++) {
        let x = res.x_values[i];

        ideal_distribution = [...ideal_distribution, [x, ideal[i]]];
      }

      for (let i = 0; i < results.length; i++) {
        let distribution = results[i]["Distribution"];
        let distributionAxis = [];
        for (let i = 0; i < res.x_values.length; i++) {
          let x = res.x_values[i];
          distributionAxis = [...distributionAxis, [x, distribution[i]]];
        }
        results[i]["distributionAxis"] = distributionAxis;
      }

      this.results = res.results;
      this.ideal_distribution = ideal_distribution;
      this.x_values = res.x_values;
      if (this.results.length) {
        this.chartChooseActive = [0];

        this.getchart();
      }
    },
    getchart() {
      if (!this.myChart) {
        var chartDom = this.$refs.closestPacking;
        this.myChart = this.$echarts.init(chartDom);
      }

      let series = [];
      let nameList = [];
      for (let i = 0; i < this.results.length; i++) {
        if (this.chartChooseActive.includes(i)) {
          let result = this.results[i];
          let name = i + 1 + "";
          nameList = [...nameList, name];
          series.push({
            name,
            type: "line",
            symbol: "none",
            data: result["distributionAxis"],
          });
        }
      }
      if (series.length) {
        let idealname = "理想";
        nameList = [...nameList, idealname];
        series.push({
          name: idealname,
          type: "line",
          symbol: "none",
          data: this.ideal_distribution,
        });
      }

      this.myChart.setOption(
        {
          tooltip: {
            show: true,
            trigger: "axis",

            axisPointer: {
              type: "shadow",
            },

            textStyle: {
              fontSize: 12,
            },
          },
          dataZoom: [
            {
              type: "inside",
              xAxisIndex: 0,
              zoomOnMouseWheel: true, //滚轮是否触发缩放
              moveOnMouseMove: true, //鼠标滚轮触发滚动
              moveOnMouseWheel: true,
            },
            {
              bottom: 70,
              type: "slider",
            },
          ],
          toolbox: {
            show: true,
            feature: {
              restore: {
                show: true,
              },
              dataZoom: {
                show: true,
              },
              saveAsImage: {
                show: true,
              },
            },
          },
          legend: {
            x: "center",
            y: "bottom",
            data: nameList,
          },
          grid: {
            left: "20",
            right: "20",
            bottom: "100",
            containLabel: true,
          },
          xAxis: {
            logBase: 10,
            type: "log",
            min: 0.01,
          },
          yAxis: {},
          series,
        },
        true
      );
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
 <style src="@/assets/powder.scss" scoped lang="scss"></style>